class RegionsController < ApplicationController
  before_filter :find_book
  
  # GET /books/1/pages/1/regions
  # GET /books/1/pages/1/regions.xml
  def index
    @regions = @page.regions

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @regions }
    end
  end

  # GET /books/1/pages/1/regions/1
  # GET /books/1/pages/1/regions/1.xml
  def show
    @region = @book.regions.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @region }
    end
  end

  # GET /books/1/pages/1/regions/new
  # GET /books/1/pages/1/regions/new.xml
  def new
    @region = @book.regions.build(:page_id=>params[:page_id])

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @region }
    end
  end

  # GET /books/1/pages/1//regions/1/edit
  def edit
    @region = @book.regions.find(params[:id])
  end

  # POST /books/1/pages/1/regions
  # POST /books/1/pages/1/regions.xml
  def create
    @region = @book.regions.build(params[:region])

    respond_to do |format|
      if @region.save
        flash[:notice] = 'Region was successfully created.'
        format.html { redirect_to book_page_region_path(@region.book, @region.page_id, @region) }
        format.xml  { render :xml => @region, :status => :ok, :location => book_page_region_path(@region.book, @region.page_id, @region) }
      else
        format.html { render :action => "new", :location=>book_page_regions_path(params[:book_id], params[:page_id]) }
        format.xml  { render :xml => @region.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /books/1/pages/1/regions/1
  # PUT /books/1/pages/1/regions/1.xml
  def update
    @region = @book.regions.find(params[:id])

    respond_to do |format|
      if @region.update_attributes(params[:region])
        flash[:notice] = 'Region was successfully updated.'
        format.html { redirect_to book_page_region_path(@region.book,@region.page_id,@region)}
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @region.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /books/1/pages/1/regions/1
  # DELETE /books/1/pages/1/regions/1.xml
  def destroy
    @region = @book.regions.find(params[:id])
    @region.destroy

    respond_to do |format|
      format.html { redirect_to(book_page_regions_url(@region.book, @region.page_id)) }
      format.xml  { head :ok }
    end
  end
  
  protected
  def find_book
    @book = Book.find(params[:book_id])
    @page = @book.pages[params[:page_id].to_i]
    params[:region].update(:page_id=>params[:page_id]) if params[:page_id] && params[:region]
  end
end
